#!/bin/sh
#
# Auto connect bluetooth controllers
#

BOARD=$(cat /boot/boot/batocera.board)

case "$1" in
    start)
        # Restores old settings saved in userdata
        batocera-bluetooth restore
        enabled="$(/usr/bin/batocera-settings-get controllers.bluetooth.enabled)"
        ps3_enabled="$(/usr/bin/batocera-settings-get controllers.ps3.enabled)"
        if [ "$enabled" = "1" ] && [ "$ps3_enabled" = "1" ]
        then 
            /usr/bin/batocera-settings-set -f /etc/bluetooth/input.conf ClassicBondedOnly false
        else
            /usr/bin/batocera-settings-set -f /etc/bluetooth/input.conf ClassicBondedOnly true
        fi

        [ "$enabled" = "1" ] || exit 0
        # soft unblock bluetooth
        rfkill unblock bluetooth

        #Start hciattach for applicable boards
        bluetoothstack="@INTERNAL_BLUETOOTH_STACK@"
        for i in $bluetoothstack
        do
            case $i in
                kvim4)
                    /usr/bin/hciattach -s 115200 /dev/ttyS1 bcm43xx 2000000
                    sleep 3 # Give hciattach a few seconds to finish attaching firmware
                    /usr/bin/hciconfig hci0 up
                ;;
                rfkreset)
                    echo 0 > /sys/class/rfkill/rfkill0/state
                    sleep 1
                    echo 1 > /sys/class/rfkill/rfkill0/state
                    sleep 1
                ;;
                bcm150)
                    # Bluetooth on the OrangePi 4-LTS board is handled by a Spreadtrum (sprd) chip
                    # and requires a custom hciattach_opi binary
                    if [ ${BOARD} = "orangepi4-lts" ] || [ ${BOARD} = "orangepi-800" ]
                    then
                        /usr/bin/hciattach_opi -n -s 1500000 /dev/ttyBT0 sprd &
                    else
                        /usr/bin/hciattach /dev/ttyS0 bcm43xx 1500000 flow nosleep &
                    fi
                    sleep 2 # Give hciattach a few seconds to finish attaching firmware
                ;;
                rtk115)
                    /usr/bin/hciattach -n /dev/ttyS0 rtk_h5 115200 & # specific to Tinkerboard
                    sleep 2 # Give hciattach a few seconds to finish attaching firmware
                ;;
                bcm921)
                    /usr/bin/hciattach /dev/ttyAMA0 bcm43xx 921600
                ;;
                piscan)
                    /usr/bin/hciconfig hci0 up piscan # specific rpi
                    sleep 2 # without the sleep, on rpi4, the agent fails on startup complaining the device is not here
                ;;
                sprd)
                    /usr/bin/hciattach_opi -n -s 1500000 /dev/ttyBT0 sprd & # specific for certain orangepi boards
                    sleep 2
                ;;
                bcm4345c5)
                    /usr/bin/brcm_patchram_plus --enable_hci --no2bytes --tosleep 200000 \
                        --baudrate 1500000 --patchram /lib/firmware/BCM4345C5.hcd /dev/ttyAS1 &
                    sleep 2
                ;;
                bcm4345c0)
                    bt_status=$(cat /proc/device-tree/wireless-bluetooth/status)
                    wifi_chip=$(cat /proc/device-tree/wireless-wlan/wifi_chip_type)
                    if [[ "${wifi_chip}" == "ap6256" && "${bt_status}" == "okay" ]]; then
                        brcm_patchram_plus --enable_hci --no2bytes --use_baudrate_for_download --tosleep 200000 \
                            --baudrate 1500000 --patchram /lib/firmware/BCM4345C0.hcd /dev/ttyS1 &
                        sleep 2
                    fi
                ;;
                syn43711a0)
                    if [ ${BOARD} = "orangepi-5-ultra" ] || [ ${BOARD} = "orangepi-5-max" ]; then
                        rfkill unblock all
                        brcm_patchram_plus --enable_hci --no2bytes --use_baudrate_for_download --tosleep 200000 \
                            --baudrate 1500000 --patchram /lib/firmware/SYN43711A0.hcd /dev/ttyS7 &
                        sleep 2
                    fi
                ;;
                aic8800)
                    if [ ${BOARD} = "coolpi-4b" ]; then
                        rfkill unblock all
                        /usr/bin/hciattach -n /dev/ttyS1 any 1500000 &
                        sleep 2
                    fi
                ;;
            esac
        done

        btaddr="$(/usr/bin/batocera-settings-get bluetooth.adapter)"
        settings_version="$(/usr/bin/batocera-settings-get controllers.ps3.driver)"
        if [ "$settings_version" != "bluez" ]
        then
            BLUETOOTHD_ARGS="--noplugin=sixaxis"
        else
            BLUETOOTHD_ARGS="--noplugin=sixaxispair"
        fi

        if [ "$ps3_enabled" != "1" ]
        then 
            BLUETOOTHD_ARGS="--noplugin=sixaxis,sixaxispair"
        fi

        debug="$(/usr/bin/batocera-settings-get controllers.bluetooth.debug)"
        if test "${debug}" = 1
        then
            start-stop-daemon -S -q -m -p /var/run/bluetoothd.pid --exec \
                /usr/libexec/bluetooth/bluetoothd -- -n -d $BLUETOOTHD_ARGS 2>/var/log/bluetooth-daemon.log &
        else
            start-stop-daemon -S -q -m -p /var/run/bluetoothd.pid --exec \
                /usr/libexec/bluetooth/bluetoothd -- $BLUETOOTHD_ARGS &
        fi

        if [ -n "${btaddr}" ]
        then
            start-stop-daemon -S -q -m -p /var/run/bluetooth-agent.pid --exec \
                /usr/bin/batocera-bluetooth-agent -- --device "${btaddr}" &
        else
            start-stop-daemon -S -q -m -p /var/run/bluetooth-agent.pid --exec \
                /usr/bin/batocera-bluetooth-agent &
        fi
        # for OrangePi LTS devices we need to power on the controller & put in pairable mode
        if [ ${BOARD} = "orangepi4-lts" ] || [ ${BOARD} = "orangepi-3-lts" ] || [ ${BOARD} = "orangepi-zero2" ] || [ ${BOARD} = "orangepi-800" ]
        then
            bluetoothctl power on
            bluetoothctl pairable on
        fi
    ;;

    stop)
        start-stop-daemon -K -q -p /var/run/bluetooth-agent.pid
        start-stop-daemon -K -q -p /var/run/bluetoothd.pid
        killall hciattach >/dev/null 2>&1
        killall hciattach_opi >/dev/null 2>&1
        killall brcm_patchram_plus >/dev/null 2>&1
        batocera-bluetooth save
    ;;

    restart|reload)
        "$0" stop
        "$0" start
    ;;

    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?
